<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  __DIR__ .'/../global_default_function.php';

function getRealTimeFeedData($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/feed/v1/ReportFeedService/getRealTimeFeedData', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	if( $bodyArray['header']['desc'] != 'success' ) {
		return;
	}
	$campaignArray = [];
	$queryCampaign = $database->query("select campaignId from cfg_campaign where `companyId` = '{$user['companyId']}' AND `userType` = 2 AND `userId` = '{$user['userid']}' ");
	if(is_array($queryCampaign)) {
		foreach ($queryCampaign as $value ) {
			array_push($campaignArray, $value['campaignId']);
		}
	}
	if( count($campaignArray) == 0 ) {
		return;
	}
	$getDate = date('Y-m-d');
	foreach ($bodyArray['body']['data'] as $value ) {
		$rebate = empty($user['rebate']) ? 0 : $user['rebate'];
		$impression = isset($value['kpis'][0]) ? $value['kpis'][0] : 0;
		$clicks     = isset($value['kpis'][1]) ? $value['kpis'][1] : 0;
		$cost       = isset($value['kpis'][2]) ? $value['kpis'][2] : 0;
		$username   = isset($value['name'][0]) ? $value['name'][0] : 0;
		$campaign   = isset($value['name'][1]) ? $value['name'][1] : 0;
		$date       = isset($value['date']) ? $value['date'] : date('Y-m-d');
		$ctr        = isset($value['kpis'][3]) ? round($value['kpis'][3], 2) : 0;
		$cpc        = isset($value['kpis'][4]) ? round($value['kpis'][4], 2) : 0;
		$userid     = isset($value['relateIdsList'][0]) ? $value['relateIdsList'][0] : 0;
		$campaignId = isset($value['relateIdsList'][1]) ? $value['relateIdsList'][1] : 0;
		$md5        = md5( $user['companyId'] . $userid . $date . $campaignId );
		$cash       = cashPrice($rebate, $cost); //现金消费
		$datatime   = strtotime($date . ' 01:00:00');
		if(in_array($campaignId, $campaignArray)) {
			$res = $database->query("select id, rebate from cfg_search where md5 = '{$md5}' LIMIT 1");
			if( isset($res[0]['id']) ) {
				if( $getDate != $date ) {
					$rebate = $res[0]['rebate'];
					$cash = cashPrice($rebate, $cost); //现金消费
				}
				$database->query( "UPDATE cfg_search SET `bazaarId` = '{$user['bazaarId']}', `rebate` = '{$rebate}', `cash` = '{$cash}', `campaign` = '{$campaign}',
					 `impression` = '{$impression}', `clicks` = '{$clicks}', `cost` = '{$cost}', `ctr` = '{$ctr}', `cpc` = '{$cpc}' WHERE id = '{$res[0]['id']}'; ");
			} else {
				$database->query("INSERT INTO cfg_search ( `companyId`, `userType`, `bazaarId`, `username`, `userid`, `campaign`, `campaignid`, `impression`, `clicks`, `cost`, `ctr`, `cpc`, `rebate`, `cash`, `datatime`, `md5` ) values (
				'{$user['companyId']}', 2, '{$user['bazaarId']}', '{$user['username']}', '{$user['userid']}', '{$campaign}', '{$campaignId}', '{$impression}', '{$clicks}', '{$cost}', '{$ctr}', '{$cpc}', '{$rebate}', '{$cash}', '{$datatime}', '{$md5}') " );
			}
		}
	}
}

run(function() use ($argv) {
	$param = [];
	$param['startDate'] = $param['endDate'] = date('Y-m-d');
	if( count($argv) == 1 ) {
		$param['endDate'] = date("Y-m-d");
		$param['startDate'] = date("Y-m-d", strtotime("-1 day"));
		showMessage('读取信息流当日计划数据.' );
	} else {
		$param['endDate'] = date("Y-m-d", strtotime("-1 day"));
		$param['startDate'] = date("Y-m-d", strtotime("-{$argv[1]} day"));
		showMessage('读取信息流' . $argv[1] . '天前到昨天计划数据.' );
	}

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `rebate`, `bazaarId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType = 2');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $param, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'读取信息流数据.' );
				getRealTimeFeedData(json_encode (['header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
				'body'=> [
					'realTimeRequestType'=> [
						"reportType" => 701,
						"startDate" => $param['startDate'],
						"endDate" => $param['endDate'],
						"levelOfDetails" => 3,
						"statRange" => 3,
						"unitOfTime" => 5,
						"subject" => 1,
						"performanceData" => [
							'impression',
							'click',
							'cost',
							'ctr',
							'cpc'
						]
					]
				]]), $database, $user);
			});
		}
		Swoole\Coroutine::sleep(2);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');